package com.xthh._function;

import android.content.Context;
import android.util.Log;


import com.xthh._enum.HH_EnumFileType;
import com.xthh._struct.HH_T_DIR_INFO;
import com.xthh._struct.HH_T_LogServer;
import com.xthh._struct.HH_T_SystemParams;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
import java.util.StringTokenizer;

public class HH_Logging {

    //设为false关闭日志
    private static final boolean LOG_ENABLE = true;
    // 日志写入文件
    public static boolean  LOG_FILE = false;

    // 增加16进制输出
    public static void hex(String tag, byte[] array) {
        String msg = HH_HexUtil.formatHexString(array, true);
        if (LOG_ENABLE) {
            Log.i(tag, msg);
        }
    }

    public static void hex(String tag, byte[] array, int arrayLen) {
        String msg = HH_HexUtil.formatHexString(array, true, arrayLen);
        if (LOG_ENABLE) {
            Log.i(tag, msg);
        }
    }

    public static void hex(String tag, byte[] array, String title) {
        String msg = title + " " + HH_HexUtil.formatHexString(array, true);
        if (LOG_ENABLE) {
            Log.i(tag, msg);
        }
    }

    public static void hexI(String tag, int[] arrayI, int displayCount) {
        if (arrayI == null || arrayI.length <=0 )
            return;

        byte []arrayB = new byte[arrayI.length];
        for (int i = 0; i < arrayI.length; i++)
            arrayB[i] = (byte)arrayI[i];

        HH_Logging.hex(tag, arrayB, displayCount);
    }

    public static void hex(String tag, List<Byte> list, int displayCount) {
        if (list.size() <=0 )
            return;

        byte []array = new byte[list.size()];
        for (int i = 0; i < list.size(); i++)
            array[i] = list.get(i);

        HH_Logging.hex(tag, array, displayCount);
    }

    public static void hexI(String tag, List<Integer> list, int displayCount) {
        if (list.size() <=0 )
            return;

        byte []array = new byte[list.size()];
        for (int i = 0; i < list.size(); i++)
            array[i] = list.get(i).byteValue();

        HH_Logging.hex(tag, array, displayCount);
    }


    public static void v(String tag, String format, Object... args) {
        String msg = String.format(format, args);
        if (LOG_ENABLE) {
            Log.v(tag, msg);
        }
    }

    public static void d(String tag, String format, Object... args) {
        String msg = String.format(format, args);
        if (LOG_ENABLE) {
            Log.d(tag, msg);
        }
    }

    public static void w(String tag, String format, Object... args) {
        String msg = String.format(format, args);
        if (LOG_ENABLE) {
            Log.w(tag, msg);
        }
    }

    public static void e(String tag, String format, Object... args) {
        String msg = String.format(format, args);
        if (LOG_ENABLE) {
            Log.e(tag, msg);
        }
    }

    public static void i(String tag, HH_T_SystemParams tp, String format, Object... args) {
        String msg = String.format(format, args);
        if (LOG_ENABLE) {
            Log.i(tag, msg);
        }

        if (LOG_FILE)
            WriteLogToFile(tp.getCtx(), msg);
    }

    public static void i(String tag, String format, Object... args) {
        String msg = String.format(format, args);
        if (LOG_ENABLE) {
            Log.i(tag, msg);
        }

    }

    private static void WriteLogToFile(Context ctx, String msg) {
        String stringInfo = String.format("[%s] %s %s", HH_TimeUtil.GetCurrentSystemTime(), msg, "\r\n");
        String path = HH_SystemUtil.GetLogPath();
        HH_FileUtil.WriteFile(ctx, path, stringInfo, true);
    }

    // 包含函数名
    public static void i(String tag, Exception e, String format, Object... args) {
        if (!LOG_ENABLE)
            return;

        StackTraceElement[] trace = e.getStackTrace();
        if (trace == null || trace.length == 0) {
            Log.i("error", "log: get trace info failed");
            return;
        }

        if (trace[0].getClassName() == null) {
            Log.i("error", "log: get getClassName info failed");
            return;
        }
        if (trace[0].getMethodName() == null) {
            Log.i("error", "log: get getMethodName info failed");
            return;
        }

        String class_name = getSimpleClassName(trace[0].getClassName());
        String method_name = getSimpleClassName(trace[0].getMethodName());
        int lineNumber = trace[0].getLineNumber();

        String msg = String.format(format, args);
        String info = String.format("[%s]-[%s]-[%d]:%s",
                class_name != null ? class_name : "",
                method_name != null ? method_name : "",
                lineNumber,
                msg);

        Log.i(tag, info);
    }


    public static String getSimpleClassName(String fullClassName) {
        String split = ".";
        String class_name = "";
        StringTokenizer token = new StringTokenizer(fullClassName, split);
        while (token.hasMoreTokens()) {
            class_name = token.nextToken();
        }
        return class_name;
    }




    public static void LOG_UDP(HH_T_LogServer tl, String tag, String format, Object... args) {
        /*String msg = String.format(format, args);

        // 写入文件
        String stringInfo = String.format("[BLE]<%s> %s %s", TimeUtil.GetCurrentSystemTime(), msg, "\r\n");

        if (tl != null && tl.isEnable()) {
            new Thread(new Runnable() {
                public void run() {
                    SendUdpMsg(tl.getIp(), tl.getPort(), stringInfo);
                }

                private void SendUdpMsg(String ip, int port, String data) {
                    if (data == null)
                        return;

                    // 转byte
                    final byte[] bData = CharUtil.StringToByte2(data, "GB2312");

                    DatagramSocket socket = null;
                    try {
                        // 1、创建套接字
                        socket = new DatagramSocket(null);
                        SocketAddress socketAddr = new InetSocketAddress(ip, port);

                        DatagramPacket packet = new DatagramPacket(bData, bData.length, socketAddr);
                        // 4、发送数据
                        socket.send(packet);
                        // 关闭
                        if (null != socket) {
                            socket.close();
                            socket = null;
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (null != socket) {
                            socket.close();
                        }
                    }
                }


            }).start();

        }*/
    }


    public static void XTWF(HH_T_LogServer tl, Context ctx, String path, String tag, String format, Object... args) {
        String msg = String.format(format, args);
        if (LOG_ENABLE) {
            Log.i(tag, msg);
        }
        if (ctx == null || path == null)
            return;

        // 写入文件
        String stringInfo = String.format("[%s] %s %s", HH_TimeUtil.GetCurrentSystemTime(), msg, "\r\n");
        HH_FileUtil.WriteFile(ctx, path, stringInfo, true);

        if (tl != null && tl.isEnable()) {
            HH_T_DIR_INFO tdi = HH_FileUtil.GetCurFileInfo(path);
            if (tdi != null && tdi.getName() != null && tdi.getName().length() > 0) {

                new Thread(new Runnable() {
                    public void run() {

                        SendUdpMsg(tl.getIp(), tl.getPort(), String.format("[%s] = %s", tdi.getName(), stringInfo));
                    }

                    private void SendUdpMsg(String ip, int port, String data) {
                        if (data == null)
                            return;

                        // 转byte
                        final byte[] bData = HH_CharUtil.StringToByte2(data, "GB2312");

                        DatagramSocket socket = null;
                        try {
                            // 1、创建套接字
                            socket = new DatagramSocket(null);
                            SocketAddress socketAddr = new InetSocketAddress(ip, port);

                            DatagramPacket packet = new DatagramPacket(bData, bData.length, socketAddr);
                            // 4、发送数据
                            socket.send(packet);
                            // 关闭
                            if (null != socket) {
                                socket.close();
                                socket = null;
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } finally {
                            if (null != socket) {
                                socket.close();
                            }
                        }
                    }


                }).start();
            }

        }
    }

    public static void XTWF(Context ctx, String path, String tag, String format, Object... args) {
        String msg = String.format(format, args);
        if (LOG_ENABLE) {
            Log.i(tag, msg);
        }
        if (ctx == null || path == null)
            return;

        // 写入文件
        String stringInfo = String.format("[%s] %s %s", HH_TimeUtil.GetCurrentSystemTime(), msg, "\r\n");
        HH_FileUtil.WriteFile(ctx, path, stringInfo, true);
    }

}
